package com.eboss.sbs.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.eboss.sbs.R;
import com.eboss.sbs.activity.base.BaseActivity;
import com.eboss.sbs.adapter.MemberCouponListAdapter;
import com.eboss.sbs.http.API;
import com.eboss.sbs.http.HttpCallback;
import com.eboss.sbs.model.CaculateMoneyEntity;
import com.eboss.sbs.model.MemberBenifitEntity;
import com.eboss.sbs.model.MemberCouponEnitity;
import com.google.gson.reflect.TypeToken;
import com.mytools.tool.security.Base64;
import com.mytools.tool.utils.Arith;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.utils.StringUtils;
import com.mytools.tool.views.MyListView;
import com.mytools.tool.views.MyPasswordDialog;

import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PayChooseBenifitActivity extends BaseActivity {

	public static String MEMBER_BENIFIT = "MEMBER_BENIFIT";
	public static final String SQB_PAY_MONEY_INT = "SQB_PAY_MONEY_INT";
	public static final String SQB_PAY_TYPE = "SQB_PAY_TYPE";
	
	private int payAmount;
	//private int payType;
	private MemberBenifitEntity data;
	
	private MyListView listview;
	private MemberCouponListAdapter adapter;
	private List<MemberCouponEnitity> datas;
	
	private EditText et_cost_point;
	private TextView tv_cost_point_hint;
	
	private TextView btn_cost_point;
	private boolean check_cost_point = false;
	private boolean freePassword = false;	//是否免密
	private boolean isMember = false;
	private int size = 0;
	private BitSet coupon_bitset;
	
	private long currentPoint;
	private long useLimitPoint;
	private long payMoneyPoint;
	private long frequency_min;
	private long maxPoint;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		Log.e("ONCREATE ", "PayChooseBenifitActivity");
		
		mActivity = this;
		setContentView(R.layout.activity_pay_choose_benifit);
		super.onCreate(savedInstanceState);
		
		payAmount = getIntent().getIntExtra(SQB_PAY_MONEY_INT, 0);
		data = (MemberBenifitEntity) getIntent().getSerializableExtra(MEMBER_BENIFIT);
		currentPoint = data.getPoint();
		useLimitPoint = data.getPointUseMax();
		frequency_min = data.getFrequency_min();
		payMoneyPoint = (long)data.getPointChangeRate()*payAmount/100;
		
		maxPoint = currentPoint;
		if(useLimitPoint<maxPoint){maxPoint=useLimitPoint;}
		if(payMoneyPoint<maxPoint){maxPoint=payMoneyPoint;}
		
		isMember = data.isMember();
		
		String memberName = data.getMemberName();
		showView(R.id.ly_member_name, !StringUtil.isNull(memberName));
		
		freePassword = data.isFreePassword();
		datas = data.getCoupons();
		
		size = datas==null?0:datas.size();
		coupon_bitset = new BitSet(size);
		
		
		int maxCouponMoney = 0;
		int maxCouponMoneyIndex = 0;
		for (int i = 0; i < size; i++) {
			if(datas.get(i).getMoney()>maxCouponMoney){
				maxCouponMoneyIndex=i;
				maxCouponMoney = datas.get(i).getMoney();
			}
			coupon_bitset.set(i, false);
		}
		
		coupon_bitset.set(maxCouponMoneyIndex);
		
		listview = (MyListView)findViewById(R.id.listview);
		adapter = new MemberCouponListAdapter(this, datas, coupon_bitset, new MemberCouponChooseEvent());
		listview.setAdapter(adapter);
		
		initView();
	}
	
	class MemberCouponChooseEvent implements MemberCouponListAdapter.MemberCounponCheckCallback {
		@Override
		public void callback(int position) {
			boolean currentMark = coupon_bitset.get(position);
			if(currentMark){coupon_bitset.set(position, false);}
			else{
				boolean isMultiChoose = false;//当前项目是否为单选
				for (int i = 0; i < size; i++) {
					if(i==position&&datas.get(i).isCanMultiChoose()){isMultiChoose=true;}
				}
				if(!isMultiChoose){
					for (int i = 0; i < size; i++) {coupon_bitset.set(i, false);}
				}
				else{
					//清掉单选
					for (int i = 0; i < size; i++) {
						if(!datas.get(i).isCanMultiChoose()){coupon_bitset.set(i, false);}
					}
				}
				coupon_bitset.set(position, true);
			}
			
			adapter.notifyDataSetChanged();
			
		}
	}
	
	private void initView(){
		showView(R.id.next_sure, true);
		setTvText(R.id.next_sure, "不使用权益");
		setTvText(R.id.tv_title, "会员信息");
		
		//showView(R.id.ly_username, !data.isMember());
		showView(R.id.ly_username, StringUtil.isNull(data.getMemberName()));
		
		btn_cost_point = (TextView) findViewById(R.id.btn_cost_point);
		tv_cost_point_hint = (TextView) findViewById(R.id.tv_cost_point_hint);
		et_cost_point = (EditText) findViewById(R.id.et_cost_point);
		et_cost_point.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				long usePoint = 0;
				if(!StringUtil.isNull(s.toString())){
					usePoint = Integer.parseInt(s.toString());
					if(!s.toString().equals(""+usePoint)){
						et_cost_point.setText(""+usePoint);
						et_cost_point.setSelection((""+usePoint).length());
						return;
					}
					if(usePoint>maxPoint){
						toast("当前最多可用积分为"+maxPoint);
						et_cost_point.setText(""+maxPoint);
						usePoint = maxPoint;
					}
//					if (usePoint < frequency_min && frequency_min > 0){
//						toast("当前最少可用积分为"+frequency_min);
//						et_cost_point.setText(""+frequency_min);
//						usePoint=frequency_min;
//					}
					
					check_cost_point = usePoint>0?true:false;
					btn_cost_point.setSelected(check_cost_point);
					
					et_cost_point.setSelection((""+usePoint).length());//焦点到最后
				}
				else {
					et_cost_point.setText("0");
					et_cost_point.setSelection(1);
					usePoint = 0;
				}
				
				int rate = data.getPointChangeRate();
				double temp1 = Arith.mul(usePoint, 100);
				double temp = Math.floor(Arith.divide(temp1, rate));
				if (temp == 0){
					btn_cost_point.setSelected(false);
				}
				tv_cost_point_hint.setText("可抵扣 "+ StringUtils.formatIntMoney((int) temp)+" 元");
//					tv_cost_point_hint.setText("可抵扣 "+StringUtil.priceShow3((double)usePoint/rate)+" 元");


				
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});
		et_cost_point.setText("0");
		
		findViewById(R.id.btn_cost_point).setOnClickListener(this);
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);
		findViewById(R.id.next_sure).setOnClickListener(this);
		findViewById(R.id.btn_submit).setOnClickListener(this);
		
		setTvText(R.id.tv_member_name, data.getMemberName());
		setTvText(R.id.tv_member_card_no, data.getMemberCardNo());
		setTvText(R.id.tv_member_phone, data.getMobile());
		setTvText(R.id.tv_member_total_point, data.getPoint()+"点积分");
		setTvText(R.id.tv_member_total_coupon, data.getCouponNum()+"张");
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_cost_point:
				check_cost_point = !check_cost_point;
				btn_cost_point.setSelected(check_cost_point);
				if(!check_cost_point){
					et_cost_point.setText("0");
				}
			break;
			case R.id.next_sure:
				
				CaculateMoneyEntity data3 = new CaculateMoneyEntity();
				if(data.isMember()){
					data3.setMemberCardNo(data.getMemberCardNo());
					data3.setMemberName(data.getMemberName());
				}
				data3.setTradeMoney(payAmount);
				data3.setRealMoney(payAmount);
				data3.setCouponCoverMoney(0);
				data3.setPointCoverMoney(0);
				data3.setCouponNum(0);
				Intent intent = new Intent(mActivity, PayChannelChooseActivity.class);
				intent.putExtra(PayChannelChooseActivity.CACULATE_MONEY_ENTITY, data3);
				startActivity(intent);
				finish();
				
				break;
			case R.id.btn_submit:submit_pre();break;
			case R.id.titleback_btn_back:finish();break;
			default:break;
		}
		super.onClick(v);
	}
	
	private void submit_pre(){
		if(check_cost_point){
			int pointUseNum = Integer.parseInt(et_cost_point.getText().toString());
			if (pointUseNum < frequency_min){toast("当前最小使用积分为"+frequency_min);return;}
			if(pointUseNum==0){toast("请输入使用积分数目");return;}
			else if(pointUseNum>data.getPoint()){toast("抵扣积分大于账户积分");return;}
		}
		if(!isMember&&StringUtil.isNull(data.getMemberName())){
			String memberName = getTvText(R.id.tv_member_username);
			if(StringUtil.isNull(memberName)){toast("请输入会员名");return;}
		}
		
		String couponStr = getCouponString();
		if((!StringUtil.isNull(couponStr)||check_cost_point)&&!freePassword){
			input_password();
		}
		else{
			submit_exe("");
		}
	}
	
	private void input_password(){
		final MyPasswordDialog.Builder builder = new MyPasswordDialog.Builder(this);
		builder.setTitle("输入支付密码");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				
				String password = builder.getPasswordText();
				
				if(StringUtil.isNull(password)){toast("密码不能为空!");}
				else{
					submit_exe(password);
					dialog.dismiss();
				}
			}
		});
		builder.create().show();
	}
	
	private void submit_exe(final String password){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sid", mApp.getLoginEntity().getSid());
		params.put("memberCardNo", data.getMemberCardNo());
		params.put("tradeMoney", payAmount);
		if(check_cost_point){params.put("point", Integer.parseInt(et_cost_point.getText().toString()));}
		else{params.put("point", 0);}
		
		String couponStr = getCouponString();
		
		if(!StringUtil.isNull(couponStr)){params.put("couponSn", couponStr);}
		if(check_cost_point||!StringUtil.isNull(couponStr)){
			if(isMember&&!freePassword&&!StringUtil.isNull(password)){params.put("password", Base64.getBase64(password));}
		}
		
		if(StringUtil.isNull(data.getMemberName())){params.put("memberName", getTvText(R.id.tv_member_username));}
		else{params.put("memberName", data.getMemberName());}

		API.http_post(this, API.CACULATE_MONEY, params, new HttpCallback<CaculateMoneyEntity>(this) {
			@Override
			public void onSuccess(int statusCode, CaculateMoneyEntity data2) {
				
				Intent intent = new Intent(mActivity, PayChannelChooseActivity.class);
				intent.putExtra(PayChannelChooseActivity.CACULATE_MONEY_ENTITY, data2);
				if(!freePassword){intent.putExtra("password", Base64.getBase64(password));}
				
				String couponStr = "";
				for (int i = 0; i < size; i++) {
					if(coupon_bitset.get(i)){
						if(StringUtil.isNull(couponStr)){couponStr = datas.get(i).getSn();}
						else{couponStr = couponStr+","+datas.get(i).getSn();}
					}
				}
				if(!StringUtil.isNull(couponStr)){
					intent.putExtra("couponSns", couponStr);
				}
				if(check_cost_point){intent.putExtra("pointAmount", Integer.parseInt(et_cost_point.getText().toString()));}
				startActivity(intent);
			}

			@Override
			public void onFailure(int statusCode, String message) {
				super.onFailure(statusCode, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<CaculateMoneyEntity>() {
				};
			}
		});
	}
	
	private String getCouponString(){
		String couponStr = "";
		for (int i = 0; i < size; i++) {
			if(coupon_bitset.get(i)){
				if(StringUtil.isNull(couponStr)){couponStr = datas.get(i).getSn();}
				else{couponStr = couponStr+","+datas.get(i).getSn();}
			}
		}
		return couponStr;
	}
	
}
